﻿using Lightworks.Core.Auth;
using Lightworks.Core.Cache;
using Lightworks.Core.Repository;
using Lightworks.Core.Service;
using Lightworks.Core.Utils;
using Lightworks.System.Dto;
using Lightworks.System.Models;
using System.Text;

namespace Lightworks.System.Services.Impl
{
    [Service]
    public class AuthService : IAuthService
    {
        JwtService jwtService;
        ICacheService cacheService;
        SugarRepository<User> repository;
        public AuthService(SugarRepository<User> baseRepository, JwtService jwtService,ICacheService cacheService) 
        {
            repository = baseRepository;
            this.jwtService = jwtService;
            this.cacheService = cacheService;
        }

        public LoginRes? Login(string username, string password)
        {
            var user = repository.Context.Queryable<User>()
                .Includes(x=>x.Roles)
                .First(x=>x.UserName == username);
            if (user   == null || user.Password != HashHelper.HashPwd(password, Encoding.UTF8.GetBytes(user.Salt)))
            {
                return null;
            }

            var result = new LoginRes
            {
                UserInfo = user,
                Token = jwtService.GenerateAccessToken(user.UserName!),
                RefreshToken = jwtService.GenerateRefreshToken(user.UserName!)
            };
            cacheService.Set($"system:user:detial:{user.UserName}", user);
            return result;
        }

    }
}
